package goboot

import (
	"encoding/json"
	"os"
)

func autoCodeWithConfig(aotoGoFileName string, gobootWebUrlJson string, moduleName string) {
	scanOriCode(moduleName)

	//打开文件并写入
	file, err := os.OpenFile(aotoGoFileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	jsonFile, err := os.OpenFile(gobootWebUrlJson, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		panic(err)
	}
	defer jsonFile.Close()

	file.WriteString("package main\n")
	//导包信息
	file.WriteString("import (\n")
	file.WriteString("\t\"fmt\"\n")
	//以下写入导包信息
	initWebDocMethods(true)
	if len(webDocMethodList) > 0 {
		file.WriteString("\t\"gitee.com/rainsuperman/goboot\"\n")
	}

	addedPackages := make(map[string]*bool)
	for _, method := range webDocMethodList {
		if addedPackages[method.PackageName] != nil {
			continue
		}
		addedPackages[method.PackageName] = new(bool)

		file.WriteString("\t\"" + method.StructFullPackageName + "\"\n")
	}

	file.WriteString(")\n")

	file.WriteString("func init(){\n\n")
	file.WriteString("\tfmt.Print(\"\")\n")
	//以下写入初始化路由信息

	addedStructs := make(map[string]*bool)
	for _, method := range webDocMethodList {
		if addedStructs[method.StructFullPackageName+"."+method.StructName] != nil {
			continue
		}
		file.WriteString("\tgoboot.AddRestController(\"" + method.StructFullPackageName + "\",\"" + method.StructName + "\",&" + method.PackageName + "." + method.StructName + "{})\n")

		addedStructs[method.StructFullPackageName+"."+method.StructName] = new(bool)
	}

	file.WriteString("\n}\n")

	jsonStr, _ := json.Marshal(webDocMethodList)
	jsonFile.WriteString(string(jsonStr))
	//webDocMethodList = []WebDocMethod{}

}
